<?php
/***************************************************************
*  Copyright notice
*
*  (c) 2008 Starbugs <univis2typo3@googlegroups.com>
*  All rights reserved
*
*  This script is part of the TYPO3 project. The TYPO3 project is
*  free software; you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation; either version 2 of the License, or
*  (at your option) any later version.
*
*  The GNU General Public License can be found at
*  http://www.gnu.org/copyleft/gpl.html.
*
*  This script is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU General Public License for more details.
*
*  This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/

require_once(PATH_tslib.'class.tslib_pibase.php');


/**
 * Plugin 'theses' for the 'univis2typo3' extension.
 *
 * @author	Starbugs <univis2typo3@googlegroups.com>
 * @package	TYPO3
 * @subpackage	tx_univis2typo3
 */
class tx_univis2typo3_pi5 extends tslib_pibase {
	var $prefixId      = 'tx_univis2typo3_pi5';		// Same as class name
	var $scriptRelPath = 'pi5/class.tx_univis2typo3_pi5.php';	// Path to this script relative to the extension dir.
	var $extKey        = 'univis2typo3';	// The extension key.
	var $pi_checkCHash = true;

	var $tmpl_grp_status;
	var $tmpl_grp_type;
	var $tmpl_item;
	
	/**
	 * The main method of the PlugIn
	 *
	 * @param	string		$content: The PlugIn content
	 * @param	array		$conf: The PlugIn configuration
	 * @return	The content that is displayed on the website
	 */
	function main($content,$conf)	{
		$this->conf=$conf;
		$this->pi_setPiVarDefaults();
		$this->pi_loadLL();
		
		$templateCode = $this->cObj->fileResource($this->conf['templateFile']);
		$this->template = $this->cObj->getSubpart($templateCode, '###TEMPLATE_THESIS###');

		// template subparts
		$this->tmpl_grp_status = $this->cObj->getSubpart($this->template,        '###TEMPLATE_THESIS_GROUP_STATUS###');
		$this->tmpl_grp_type   = $this->cObj->getSubpart($this->tmpl_grp_status, '###TEMPLATE_THESIS_GROUP_TYPE###');
		$this->tmpl_item       = $this->cObj->getSubpart($this->tmpl_grp_type,   '###TEMPLATE_THESIS_ITEM###');


		// Flex-Form initialisieren
		$this->pi_initPIflexForm();	
		echo $this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'what_to_display', 'sDEF');
		$content = $this->getContent($this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'what_to_display', 'sDEF'));

		return $this->pi_wrapInBaseClass($content);
	}

	function getAdvisorThesisKeys($advisor_key)
	{
	    $select  = 'thesis_key';
	    $from    = 'u_thesis_advisors';
	    $where   = "advisor ='{$advisor_key}'";
	    $groupby = $orderby = $limit = '';


            $query = $GLOBALS['TYPO3_DB']->SELECTquery(
                        $select,
                        $from,
                        $where,
                        $groupby,
                        $orderby,
                        $limit
            );
	    $items = $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
		if (mysql_num_rows($items) == 0)
			return '';

	    $result_keys = array();
            while ($item = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($items))
	    {
		$result_keys[] = "'{$item['thesis_key']}'";
	    }
	    return implode(',', $result_keys);
	}

	function getPersonalKey(){
		// find univis key of page owner
		$select  = '`tx_univis2typo3_person_key`';
		$from    = '`be_users`';
		$where   = '`uid` = ' . (int) $GLOBALS['TSFE']->page['perms_userid'];
		$groupby = $orderby = $limit = '';
		$query = $GLOBALS['TYPO3_DB']->SELECTquery(
			$select,
			$from,
			$where,
			$groupby,
			$orderby,
			$limit
		);

		$res =& $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
		$row =& mysql_fetch_assoc($res);
		$univisPersonKey =& $row['tx_univis2typo3_person_key'];
		return $univisPersonKey;
	}

	function getNitems($status = '', $advisorKey = '', $maxNumber){
		return $this->getItems($status, $advisorKey, null, $maxNumber);
	}
    
	function getItems($status = '', $advisor_key = '', $key = '', $maxNumber = 0){
	    if ('' == $advisor_key)
			$advisor_key = $this->getPersonalKey();

	    if ('' != $advisor_key)
	    {
		if ('' == $key)
		{
		    $key = $this->getAdvisorThesisKeys($advisor_key);
		}
		else
		{
		    $key .= ',' . $this->getAdvisorThesisKeys($advisor_key);
		}
	    }
		if ('' == $key)
			return null;

	    $select = 'DISTINCT *';
	    $from   = " (
			    SELECT 
			       `T1`.`key` AS `thesis_key`,
			       `T1`.`title` AS `thesis_title`,
			       `T1`.`firstname` AS `thesis_firstname`,
			       `T1`.`lastname` AS `thesis_lastname`,
			       `T1`.`public` AS `thesis_public`,
			       `T4`.`description` AS `thesis_type_description`,
			       `T4`.`description_plural` AS `thesis_type_description_plural`,
			       `T4`.`description_en` AS `thesis_type_description_en`,
			       `T4`.`description_en_plural` AS `thesis_type_description_en_plural`,
			       `T5`.`description` AS `thesis_status_description`,
			       `T5`.`description_en` AS `thesis_status_description_en`,
			       `T1`.`visible` AS `thesis_visible`,
			       `T1`.`finishdate` AS `thesis_finishdate`,
			       `T1`.`registerdate` AS `thesis_registerdate`,
			       GROUP_CONCAT(`T3`.`link` separator '; ') AS `thesis_advisors`,
			       GROUP_CONCAT(`T3`.`key` separator '; ') AS `thesis_advisors_key`
			    FROM ( (((`tx_u2t3_thesis` AS `T1`
			    LEFT JOIN `u_thesis_advisors` AS `T2`
			       ON (`T1`.`key` = `T2`.`thesis_key`))
			    LEFT JOIN `tx_u2t3_view_persons` AS `T3`
			       ON (`T2`.`advisor` = `T3`.`key`))
			    LEFT JOIN `tx_u2t3_thesis_type_order` AS `T4`
			       ON (`T1`.`type` = `T4`.`type`))
			    LEFT JOIN `tx_u2t3_thesis_status_order` AS `T5`
			       ON (`T1`.`status` = `T5`.`status`) )";
	    
	    if ('' != $key)
	    {
		$from .= "WHERE `T1`.`key` IN ({$key})";
	    }
	    
	    $from .= "
			    GROUP BY `T1`.`key`
			    ORDER BY `T5`.`key`, `T4`.`key`, `T1`.`title`
			) AS thesisSQL
			";
	    $where   = '';
	    $orderby = '';
	    $limit   = '';
	    if ($maxNumber > 0) {
		$limit = $maxNumber;
	    }


	    $query = $GLOBALS['TYPO3_DB']->SELECTquery(
			$select,
			$from,
			$where,
			$groupby,
			$orderby,
			$limit
	    );
//	    echo $query;

	    return $GLOBALS['TYPO3_DB']->sql(TYPO3_db, $query);
	}


	function open_type_box(&$item, $thesesTypeIdx) {
	    //print '> open_type_box<br />';
	    return $item[ $thesesTypeIdx ];
	}
	function close_type_box($curr_type, &$type_boxes_rendered, &$items_rendered) {
	    //print '< close_type_box<br />';
	    //global $arrMarkerType;
	    //global $type_boxes_rendered;
	    // render markers
	    $arrMarkerType['###TEMPLATE_THESIS_TYPE###'] = $curr_type;
	    $tmpl = $this->cObj->substituteMarkerArray($this->tmpl_grp_type, $arrMarkerType);
	    $type_boxes_rendered .= $this->cObj->substituteSubpart($tmpl, '###TEMPLATE_THESIS_ITEM###', $items_rendered);
	    $items_rendered = '';
	}
	function open_status_box(&$item, $thesisStatusIdx) {
	    //print '> open_status_box<br />';
	    return $item[ $thesisStatusIdx ];
	}
	function close_status_box($curr_status, &$num, &$status_boxes_rendered, &$type_boxes_rendered) {
	    //print '< close_status_box<br />';
	    // render markers
	    $arrMarkerStatus['###TEMPLATE_THESIS_STATUS_TITLE###'] = $curr_status;
	    $arrMarkerStatus['###TEMPLATE_THESIS_STATUS_COUNT###']    = (int) $num;
	    $csl = strtolower($curr_status);
	    if ('open' == $csl || 'offen' == $csl) {
		$arrMarkerStatus['###TEMPLATE_THESIS_STATUS_CLASS###'] = '-active';
	    } else {
		$arrMarkerStatus['###TEMPLATE_THESIS_STATUS_CLASS###'] = '';
	    }
	    $tmpl = $this->cObj->substituteMarkerArray($this->tmpl_grp_status, $arrMarkerStatus);
	    $status_boxes_rendered .= $this->cObj->substituteSubpart($tmpl, '###TEMPLATE_THESIS_GROUP_TYPE###', $type_boxes_rendered);
	    $type_boxes_rendered = '';
	    $num = 0;
	}

	function getContent($status = '', $advisor_key = '', $key = '')
	{
	    $items = $this->getItems($status = '', $advisor_key = '', $key = '');

	    $language = $GLOBALS["TSFE"]->sys_language_uid;
	    if ($language == 0)
	    {
		    $thesisStatusIdx = 'thesis_status_description_en';
		    //$thesisTypeIdx   = 'thesis_type_description_en';
		    $thesesTypeIdx   = 'thesis_type_description_en_plural';
	    }
	    else
	    {
		    $thesisStatusIdx = 'thesis_status_description';
		    //$thesisTypeIdx   = 'thesis_type_description';
		    $thesesTypeIdx   = 'thesis_type_description_plural';
	    }


	    // The theses page consists of three nested templates:
	    // TEMPLATE_THESIS_ITEM - displays a single record
	    // TEMPLATE_THESIS_GROUP_TYPE - displays a group of records which are of the same type
	    // TEMPLATE_THESIS_GROUP_STATUS - displays a group of type-groups which are of the same status
	    $arrMarkerStatus = array();
	    $arrMarkerType   = array();
	    $arrMarkerItem   = array();
	    $items_rendered        = '';
	    $type_boxes_rendered   = '';
	    $status_boxes_rendered = '';

	    $num = 0;

	     //Initialize content
	    $content = '';

	    //Get first entry
	    $item = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($items);

	    if ('' == $item['thesis_title']) {
		    $content .= ((1 == $language) ? 'Keine Abschlussarbeiten.' : 'No Theses, yet.');
		    return $content;
	    }

	    $curr_status = ''; // current status
	    $curr_type   = ''; // current type

	    // open first status box
	    $curr_status = $this->open_status_box($item, $thesisStatusIdx);
	    // open first type box
	    $curr_type = $this->open_type_box($item, $thesesTypeIdx);
	    do {
		$arrMarkerItem = array();

		// DEBUG
		if (4 == $num) {
		    //print_r($item);print '<br /><br />';
		}

		if ( $curr_type != $item[ $thesesTypeIdx ] ) {
		    // close previous type box
		    $this->close_type_box($curr_type, $type_boxes_rendered, $items_rendered);
		}
		if ( $curr_status != $item[ $thesisStatusIdx ] ) {
		    // close previous status box
		    $this->close_status_box($curr_status, $num, $status_boxes_rendered, $type_boxes_rendered);
		    // open new status box
		    $curr_status = $this->open_status_box($item, $thesisStatusIdx);
		}
		if ( $curr_type != $item[ $thesesTypeIdx ] ) {
		    // open new type box
		    $curr_type = $this->open_type_box($item, $thesesTypeIdx);
		}

		if (!$item['thesis_registerdate']) {
		    $item['thesis_registerdate'] = (1 == $language) ? 'sofort' : 'immediately';
		}
		$studentName = trim($item['thesis_firstname'] . ' ' . $item['thesis_lastname']);
		if ('' != $studentName) {
		    $studentName = htmlentities($studentName) . ':<br />';
		}
		$arrMarkerItem['###TEMPLATE_THESIS_NUM###']       = ++$num . 'x';
		$arrMarkerItem['###TEMPLATE_THESIS_NAME###']      = $studentName;
		$arrMarkerItem['###TEMPLATE_THESIS_TITLE###']     = htmlentities($item['thesis_title']);
		$arrMarkerItem['###TEMPLATE_THESIS_DOZENT###']    = ((1 == $language) ? 'Betreuer' : 'Advisors') . ': ' . $item['thesis_advisors'];
		$arrMarkerItem['###TEMPLATE_THESIS_STARTDATE###'] = ((1 == $language) ? 'Beginn' : 'Begin')      . ': ' . $item['thesis_registerdate'];

		$items_rendered .= $this->cObj->substituteMarkerArray($this->tmpl_item, $arrMarkerItem);
	    } while($item = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($items));

	    // close last type box
	    if ('' != $curr_type) {
		$this->close_type_box($curr_type, $type_boxes_rendered, $items_rendered);
	    }

	    // close last status box
	    if ('' != $curr_status) {
		$this->close_status_box($curr_status, $num, $status_boxes_rendered, $type_boxes_rendered);
	    }


	    //$content = $this->cObj->substituteSubpart($this->template, '###TEMPLATE_THESIS_GROUP_STATUS###', $status_boxes_rendered);

	    $arrSubpart['###TEMPLATE_THESIS_GROUP_STATUS###'] = $status_boxes_rendered;
	    $content = $this->cObj->substituteMarkerArrayCached($this->template, array(), $arrSubpart);

	    return $content;
	}
}

if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/univis2typo3/pi5/class.tx_univis2typo3_pi5.php'])	{
	include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/univis2typo3/pi5/class.tx_univis2typo3_pi5.php']);
}

?>
